package com.csht.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.swing.plaf.synth.SynthSpinnerUI;

import com.csht.page.SystemContext;

/**
 * 分页过滤器
 * @author chenhuiyan
 *
 */
public class PagerFilter implements Filter {
	
	/**
	 * 消息通知每页记录数
	 */
	private int noticePageSize;
	
	/**
	 * 留言每页记录数
	 */
	private int messagePageSize;
	
	/**
	 * 商品列表每页记录数
	 */
	private int goodsListPageSize;

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		int offset = 0;
		try {
			offset = Integer.parseInt(request.getParameter("pager.offset"));
		}catch(NumberFormatException e) {
			
		}
		
		try {
			SystemContext.setOffset(offset);
			SystemContext.setNoticePageSize(noticePageSize);
			SystemContext.setMessagePageSize(messagePageSize);
			SystemContext.setGoodsListPageSize(goodsListPageSize);
			chain.doFilter(request, response);
		}finally {
			SystemContext.removeOffset();
			SystemContext.removeNoticePageSize();
			SystemContext.removeMessagePageSize();
			SystemContext.removeGoodsListPageSize();
		}
	}
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException{
		try {
			noticePageSize = Integer.parseInt(filterConfig.getInitParameter("noticePageSize"));
			messagePageSize = Integer.parseInt(filterConfig.getInitParameter("messagePageSize"));
			goodsListPageSize = Integer.parseInt(filterConfig.getInitParameter("goodsListPageSize"));
			System.out.println("消息通知每一页记录数:" + noticePageSize);
			System.out.println("商品留言每一页记录数:" + messagePageSize);
			System.out.println("商品列表每页记录数:" + goodsListPageSize);
		}catch(NumberFormatException e) {
			noticePageSize = 8;
			messagePageSize = 4;
			goodsListPageSize = 20;
		}
	}

}
